//
//  ThemeDownload.m
//  MZBasic
//
//  Created by Better on 2022/9/13.
//

#import "ThemeDownload.h"
#import "SSZipArchive.h"

@interface ThemeDownload ()

@property (strong,nonatomic) NSFileManager *fileManager;

@end

@implementation ThemeDownload

+ (void) downloadThemeFileWithUrl:(NSString *)url
                               FilePath:(NSString *)path
                               Success:(void(^)(BOOL isSuccess))success
                               Failure:(void(^)(BOOL isFailure))failure{
//    NSURL *urlFile = [NSURL URLWithString:@"https://commonweb.bizgo.com/IOS/Theme/theme2.zip"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *urlFile = [NSURL URLWithString:url];
        NSURLRequest *request = [NSURLRequest requestWithURL:urlFile];
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            dispatch_async(dispatch_get_main_queue(), ^{
                if (error) {
                    NSLog(@"error:%@",error.localizedDescription);
                    failure(YES);
                }

                if (data) {
                    //存储.zip
                    [self storeDownloadThemezipWithData:data WithPath:path];
                    //解压
                    [self upzipWithPath:path];
                    //读取文件--解析
        //            [self readfile];
                    success(YES);
                }
            });
        }];
        [task resume];
    });
    
}

+ (void)storeDownloadThemezipWithData:(NSData *)data WithPath:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isExists = [fileManager fileExistsAtPath:[self zipPath:path]];
     if(isExists){
         [fileManager removeItemAtPath:[self zipPath:path] error:nil];
     }
    [fileManager createFileAtPath:[self zipPath:path] contents:data attributes:nil];
}
+ (NSString *)zipPath:(NSString *)path{//下载路径
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString*pathCache=[paths objectAtIndex:0];
    NSString *zipPath = [NSString stringWithFormat:@"/%@/%@.zip",pathCache,path];
    return zipPath;
}
+ (NSString *) upZipPath:(NSString *)path{//读取路径
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString*pathCache=[paths objectAtIndex:0];
    NSString *upZipPath = [NSString stringWithFormat:@"/%@/%@",pathCache,path];
    return upZipPath;
}
+ (NSString *) onlyUpZipPath:(NSString *)path{//解压路径
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString*pathCache=[paths objectAtIndex:0];
    NSString *upZipPath = [NSString stringWithFormat:@"/%@",pathCache,path];
    return upZipPath;
}
+ (BOOL) upzipWithPath:(NSString *)path{//解压
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断此目录是否有文件，有的话删除此文件--Theme
    BOOL isExists = [fileManager fileExistsAtPath:[self upZipPath:path]];
    if(isExists){
        [fileManager removeItemAtPath:[self upZipPath:path] error:nil];
    }
    
    BOOL result = [SSZipArchive unzipFileAtPath:[self zipPath:path]
                                  toDestination:[self onlyUpZipPath:path]];
    if (result) {
        //解压缩完成把压缩文件删除，节省内存
        BOOL isExists = [fileManager fileExistsAtPath:[self zipPath:path]];
         if(isExists){
             [fileManager removeItemAtPath:[self zipPath:path] error:nil];
         }
    }
    return  result;
}
@end
